<?php
namespace app\store\controller\parent;


use app\store\controller\Base;
use app\store\controller\Weixin;
use think\Db;
use think\Exception;
use think\Session;

header("Content-type:text/html;charset=utf-8");

class Vote extends Base
{

    public function index()
    {
        Session::set('uid',input('uid'));
        Session::set('shop_id',input('shop_id'));
        //活动列表 暂定
        $this->shop_id = Session::get('shop_id');
        //广告图
        $banner_info =  Db('banner')
            ->where('shop_id',3)
            ->where('is_show',1)
            ->where('is_del',0)
            ->field('pic_url,url')
            ->select();
        $this->assign('banner_info',$banner_info);
        //参赛活动图
        $list =  Db('vote_act')
            ->where('shop_id',$this->shop_id)
            ->where('status',0)
            ->where('is_del',0)
            ->field('id as act_id,title,pic_url')
            ->select();
        $this->assign('list',$list);
        $this->assign('shop_id',$this->shop_id);
        return $this->fetch();
    }


    /**
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * 参赛详情
     */
    public function join_detail()
    {
        //活动id
        if(input('act_id')){
            $act_id = input('act_id');
        }else{
            $act_id = Db('vote_player')->where('id',input('send_uid'))->value('act_id');
        }

        //来自分享
        if(input('send_uid')){
            $send_uid = input('send_uid');
        }else{
            $send_uid = Db('vote_player')->where('act_id',$act_id)->where('parent_id',$this->uid)->value('id');
        }

        //待投票选手id
        $this->assign('send_uid',$send_uid);

        //家长id
        $this->assign('uid',$this->uid);

        //来自分享
        if(input('status')){
            $this->assign('from',input('status'));
        }else{
            $this->assign('from','');
        }

        //用户信息
        if (input('back_info')){
            $userInfo = json_decode(input('back_info'),true);

            // 验证用户是否存在
            $u_info = Db::name('users')
                ->where('openid',$userInfo['openid'])
                ->find();

            // 用户已存在
            if(!empty($u_info) && isset($u_info)){

                // 写入缓存
                Session::set('openid',$userInfo['openid']);
                Session::set('uid',$u_info['uid']);
                // 用户首次访问
            }else{

                $params['nickname']     = $userInfo['nickname'];        // 微信昵称
                $params['openid']       = $userInfo['openid'];          // openid
                $params['sex']          = $userInfo['sex'];             // 性别 1男士 2女士
                $params['create_time']  = time();                       // 注册时间

                $in_id = Db::name('users')->insertGetId($params);

                Session::set('openid',$userInfo['openid']);
                Session::set('uid',$in_id);

            }

        }

        $list = Db('vote_act')->where('id',$act_id)->where('is_del',0)->where('status',0)->find();
        $this->assign('list',$list);

        //查看前十名
        $player_list = Db('vote_player') ->where('act_id',$act_id)->order('vote_num desc')->select();
        if ($player_list){
            foreach ($player_list as $k=>$v){
                $player_list[$k]['percent'] =  round($v['vote_num']/$list['vote_limit']*100,2);
            }
            $this->assign('player_list',$player_list);
        }else{
            $this->assign('player_list','');
        }

        //已参加的选手信息
        $player_info =  Db('vote_player')
            ->where('parent_id',$this->uid)
            ->where('status',0)
            ->where('check','neq',2)
            ->where('act_id',$act_id)
            ->find();

        if (!empty($player_info)){
            $player_info['pic_url']=json_decode($player_info['pic_url']);
            $this->assign('player_info',$player_info);
            $this->assign('banner_info','');
            $percent =  round($player_info['vote_num']/$list['vote_limit']*100,2);
            $this->assign('percent',$percent);
        }else{
            //未参与时广告图
            $banner_info =  Db('banner')
                ->where('is_show',1)
                ->where('is_del',0)
                ->field('pic_url,url')
                ->select();
            $this->assign('player_info','');
            $this->assign('banner_info',$banner_info);
        }



        //待审核信息
        $check_info =  Db('vote_player')
            ->where('parent_id',$this->uid)
            ->where('status',0)
            ->where('check',0)
            ->where('act_id',$act_id)
            ->find();
        $this->assign('check_info', $check_info);

        $weixin = new Weixin($this->shop_id);
        $url = request()->domain() . $this->request->url();
        $js_config = $weixin->js_config($url);
        $this->assign('jsconfig', $js_config);
        $this->assign('shop_id',$this->shop_id);

        // 微信获取授权地址
        $wx_request_url = request()->domain() . url("wchat/oauth/getwxinfo");

        //回调地址
        $param['send_uid']= $send_uid;
        $param['status']= 1;
        $call_bacl_url  = request()->domain() .url("store/parent.vote/join_detail",$param);

        //分享地址链接
        $link_url  = $wx_request_url . "?shop_id={$this->shop_id}&call_back={$call_bacl_url}";
        $this->assign('link_url',$link_url);

        //分享图片链接


        return $this->fetch();
    }


    /**
     * @return mixed
     * 报名参赛
     */

    public function add()
    {
        $act_id = input('act_id');
        $this->assign('act_id', $act_id);

        if(input('shop_id')){
            $shop_id = input('shop_id');
            $this->shop_id = $shop_id;
        }

        if(input('uid')){
            $this->uid = input('uid');
        }

        $this->assign('shop_id', $this->shop_id);

        if(request()->isAjax()){

            $d = input();
            $data['act_id'] = $d['act_id'];
            $data['name'] = $d['name'];
            $data['age'] = $d['age'];
            $data['sex'] = $d['sex'];
            $data['pic_url'] = json_encode($d['pic_url']);
            $data['tel'] = $d['tel'];
            $data['shop_id'] = $this->shop_id;
            $data['create_time'] = time();
            $data['parent_id'] = $this->uid;


            $res = Db::name('vote_player')->insert($data);

            if($res){
                $this->success('信息提交成功,请耐心等待审核呦~');
            }else{
                $this->error('信息提交失败');
            }
        }


        $weixin = new Weixin($this->shop_id);
        $url = request()->domain() . $this->request->url();
        $js_config = $weixin->js_config($url);
        $this->assign('jsconfig', $js_config);

        return $this->fetch();
    }

    /**
     *自己给自己投票
     */
    public function hit_own(){

        if(request()->isAjax()) {

            $player_id = input('player_id');
            $user_info = Db('users')->where('uid',$this->uid)->field('openid,nickname')->find();
            $act_id =  Db('vote_player')->where('id',$player_id)->value('act_id');

            //这个活动已经被投的票数
            $act_list = Db('vote_recode')
                ->where('act_id',$act_id)
                ->field('vote_time,act_id')
                ->count();

            //这个人为这个活动总投的票数
            $list = Db('vote_recode')
                ->where('openid',$user_info['openid'])
                ->where('act_id',$act_id)
                ->field('vote_time,act_id')
                ->count();
            $time1 = strtotime(date('Y-m-d'));
            $time2 = strtotime(date('Y-m-d',strtotime('+1 day')));

            //这个人今天为这个活动投的票数
            $limit_vote = Db('vote_recode')
                ->where('openid',$user_info['openid'])
                ->where('act_id',$act_id)
                ->where('vote_time',['>',$time1],['<',$time2])
                ->field('vote_time,act_id')
                ->count();

            //这个活动的票数限制
            $act_info =Db('vote_act')->where('id',$act_id)->find();

            if ($act_list<$act_info['vote_limit']){
                if ($list<$act_info['total_limit']){
                    if ($limit_vote<$act_info['day_limit']){
                        $data  = [
                            'player_id' => $player_id,
                            'act_id'    => $act_id,
                            'vote_time' =>time(),
                            'openid'    => $user_info['openid'],
                            'nickname'  => $user_info['nickname']
                        ];
                        Db::startTrans();
                        try{
                            Db('vote_player')->where('id',$player_id)->setInc('vote_num');
                            Db('vote_recode')->insert($data);
                            Db::commit();
                        }catch (\Exception $e){
                            Db::rollback();
                            $this->error('投票失败');
                        }
                        $this->success('投票成功,感谢您投上宝贵的一票');
                    }else{
                        $this->error('今天投票已上限');
                    }
                }else{
                    $this->error("不能再投了");
                }
            }else{
                $this->error('总票数已达上限');
            }

        }
    }

    /**
     * 别人点击投票
     */
    public function hit(){

        if(request()->isAjax()) {

            $send_uid = input('send_uid');
            $act_id =  Db('vote_player')->where('id',$send_uid)->value('act_id');
            $player_id = Db('vote_player')->field('id,check')->where('id',$send_uid)->find();

            if($player_id['check']!=1){
                $this->error('该选手暂未通过审核');
            }
            $user_info = Db('users')->where('uid',$this->uid)->field('openid,nickname')->find();



            //这个活动已经被投的票数
            $act_list = Db('vote_recode')
                ->where('act_id',$act_id)
                ->field('vote_time,act_id')
                ->count();

            //这个人为这个活动总投的票数
            $list = Db('vote_recode')
                ->where('openid',$user_info['openid'])
                ->where('act_id',$act_id)
                ->field('vote_time,act_id')
                ->count();
            $time1 = strtotime(date('Y-m-d'));
            $time2 = strtotime(date('Y-m-d',strtotime('+1 day')));

            //这个人今天为这个活动投的票数
            $limit_vote = Db('vote_recode')
                ->where('openid',$user_info['openid'])
                ->where('act_id',$act_id)
                ->where('vote_time',['>',$time1],['<',$time2])
                ->field('vote_time,act_id')
                ->count();

            //这个活动的票数限制
            $act_info =Db('vote_act')->where('id',$act_id)->find();

            if ($act_list<$act_info['vote_limit']){
                if ($list<$act_info['total_limit']){
                    if ($limit_vote<$act_info['day_limit']){
                        $data  = [
                            'player_id' => $player_id['id'],
                            'act_id'    => $act_id,
                            'vote_time' =>time(),
                            'openid'    => $user_info['openid'],
                            'nickname'  => $user_info['nickname']
                        ];
                        Db::startTrans();
                        try{
                            Db('vote_player')->where('id',$player_id['id'])->setInc('vote_num');
                            Db('vote_recode')->insert($data);
                            Db::commit();
                        }catch (\Exception $e){
                            Db::rollback();
                            $this->error('投票失败');
                        }
                        $this->success('投票成功,感谢您投上宝贵的一票');
                    }else{
                        $this->error('今天投票已上限');
                    }
                }else{
                    $this->error("不能再投了");
                }
            }else{
                $this->error('总票数已达上限');
            }

        }
    }

}
